// pages/goods/category.js
var app = getApp();
var rootDocment = app.globalData.postUrl;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        navHeight: app.globalData.barInfo.navHeight, //导航栏高度
        topOpacity: 0,

        windowHeight: 100,
        hiddenLoading: false,
        currentItem: '',
        catList1: [],
        catList2: [],
        tabber: {},
        active: 1,
        goodsList: [],
        perPage: 20,
        curPage: 1,
        class_id: 103,
        is_vip_price: JSON.parse(wx.getStorageSync('is_vip_price') || 'false'),
        userInfo: {},

        list1Text: '',
        list2Text: '',
        list3Text: '',

        list1: ['女友/老婆', '男友/老公', '同事', '儿童'],
        list2: [],
        list3: [{
                name: '恋爱',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_1.png",
            },
            {
                name: '生日',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_2.png"
            },
            {
                name: '商务送礼',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_3.png"
            },
            {
                name: '新生/满月',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_4.png"
            },
            {
                name: '日常伴手礼',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_5.png"
            },
            {
                name: '暖房',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_6.png"
            },
            {
                name: '聚会',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_7.png"
            },
            {
                name: '踏青',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_8.png"
            },
            {
                name: '拜访',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_9.png"
            },
            {
                name: '婚宴',
                icon: "https://lhs.tann.cc/upload/images/new/gift_icon_10.png"
            },
        ],

        // 双滑块相关数据
        sliderPoints: ['0', '50', '200', '500', '1K', '2K', '不限'],
        minValue: 0,
        maxValue: function () {
            return this.sliderPoints.length - 1;
        }, // 动态计算
        currentMin: 0,
        currentMax: 5, // 可以在onLoad中动态设置为sliderPoints.length - 1
        // 触摸相关状态
        isDragging: false,
        draggingHandle: null, // 'min' 或 'max'
        sliderWidth: 0,
        isExpanded: false,
    },

    onPageScroll: function (e) {
        if (e.scrollTop > 50) {
            let opacity = e.scrollTop / 300;
            opacity = opacity > 1 ? 1 : opacity;
            this.setData({
                topOpacity: opacity
            });
        } else {
            this.setData({
                topOpacity: 0
            });
        }
    },

    onShow() {
        var that = this

        this.setData({
            is_shop: wx.getStorageSync('is_shop') || 0,
        })

        //用户授权登录
        if (app.globalData.userInfo.userID) {
            app.login(function (userInfo) {
                that.setData({
                    userInfo: userInfo,
                    is_vip_price: userInfo.is_vip_price
                });
            });
        }
        this.getInfoApi()
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        app.editTabbar();
        //初始化
        this.setCategoryData();
        //获取设备窗口信息

        // 动态设置currentMax
        this.setData({
            currentMax: this.data.sliderPoints.length - 1
        });

    },
    onChange(event) {

        this.setData({
            class_id: event.detail.name.id
        })
        this.setGoodsListData(event.detail.name.id)
    },
    //初始化分类
    setCategoryData: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['pid'] = 0;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_goods_category',
            data: {
                pid: paraArr['pid'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                res.data.unshift({
                    title: "全部",
                    wap_title: "全部",
                    id: 0
                })
                that.setData({
                    catList1: res.data,
                    currentItem: res.data[0].id
                });
                that.setGoodsListData(res.data[0].id);
            }
        })
    },

    //初始化子类
    setChildCategoryData: function (id) {
        var that = this;
        var paraArr = new Array();
        paraArr['pid'] = id;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_goods_category',
            data: {
                pid: paraArr['pid'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    catList2: res.data
                });
            }
        })
        that.setData({
            currentItem: id,
            hiddenLoading: true
        });
    },

    //切换大类
    toggleCategory: function (e) {
        var that = this;
        var id = e.currentTarget.dataset.id
        if (!id) return;
        that.setChildCategoryData(id);
    },

    //点击小类
    goGoodsList: function (e) {
        var that = this;
        var id = e.currentTarget.dataset.id
        if (!id) return;
        console.log('goods/list', 'id=' + id);
        app.redirect('goods/list', 'id=' + id)
    },
    //初始商品列表
    setGoodsListData: function (id) {
        var that = this;
        wx.request({
            url: rootDocment + '/api_goods',
            data: {
                sort: id,
                size: that.data.perPage,
                page: that.data.curPage,
                user_id: wx.getStorageSync('user_id3') || 0,
                order: 'id',
                order_type: 'desc',
            },
            method: 'GET',
            header: {},
            success: function (res) {

                if (res.statusCode == 200) {
                    console.log(res.data.data);
                    that.setData({
                        goodsList: res.data.data
                    });
                }

                that.setData({
                    hiddenLoading: true
                });
                // if (res.data.data.length > 0) { //如果有数据
                //   var list = that.data.goodsList;
                //   for (var i = 0; i < res.data.data.length; i++) {
                //     list.push(res.data.data[i]);
                //   }
                //   that.setData({
                //     goodsList: list
                //   });
                //   if (res.data.data.length == that.data.perPage) {
                //     that.setData({
                //       curPage: that.data.curPage + 1,
                //       hiddenLoading: true
                //     });
                //   } else {
                //     that.setData({
                //       hiddenLoading: true
                //     });
                //   }
                // } else {
                //   that.setData({
                //     hiddenLoading: true

                //   });
                // }

            }
        })

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },
    // 双滑块最小值变化处理函数
    onMinChange(e) {
        const value = e.detail.value;
        if (value < this.data.currentMax) {
            this.setData({
                currentMin: value
            });
        }
    },

    // 双滑块最大值变化处理函数
    onMaxChange(e) {
        const value = e.detail.value;
        if (value > this.data.currentMin) {
            this.setData({
                currentMax: value
            });
        }
    },
    /**
     * 双滑块触摸开始事件
     * @param {Object} e 触摸事件对象
     */
    onSliderTouchStart: function (e) {
        const touch = e.touches[0];
        const rect = wx.createSelectorQuery().select('.double_slider').boundingClientRect();

        rect.exec((res) => {
            if (res && res[0]) {
                const sliderLeft = res[0].left;
                const touchX = touch.clientX - sliderLeft;
                const percentage = touchX / res[0].width;

                // 判断触摸位置距离哪个滑块更近
                const totalPoints = this.data.sliderPoints.length - 1;
                const minHandlePos = this.data.currentMin / totalPoints;
                const maxHandlePos = this.data.currentMax / totalPoints;

                const distanceToMin = Math.abs(percentage - minHandlePos);
                const distanceToMax = Math.abs(percentage - maxHandlePos);

                // 选择距离更近的滑块，或者如果都不近但在范围内，则选择最近的端点
                if (distanceToMin < distanceToMax) {
                    this.setData({
                        isDragging: true,
                        draggingHandle: 'min'
                    });
                } else {
                    this.setData({
                        isDragging: true,
                        draggingHandle: 'max'
                    });
                }

                // 立即处理一次移动，更新滑块位置
                this.updateSliderPosition(percentage);
            }
        });
    },

    /**
     * 双滑块触摸移动事件
     * @param {Object} e 触摸事件对象
     */
    onSliderTouchMove: function (e) {
        if (!this.data.isDragging) return;

        const touch = e.touches[0];
        const rect = wx.createSelectorQuery().select('.double_slider').boundingClientRect();

        rect.exec((res) => {
            if (res && res[0]) {
                const sliderLeft = res[0].left;
                const touchX = touch.clientX - sliderLeft;
                const percentage = Math.max(0, Math.min(1, touchX / res[0].width));

                this.updateSliderPosition(percentage);
            }
        });
    },

    /**
     * 双滑块触摸结束事件
     */
    onSliderTouchEnd: function () {
        this.setData({
            isDragging: false,
            draggingHandle: null
        });
    },

    /**
     * 更新滑块位置
     * @param {Number} percentage 滑块位置百分比 (0-1)
     */
    updateSliderPosition: function (percentage) {
        // 将百分比转换为最近的刻度点索引
        const totalPoints = this.data.sliderPoints.length - 1;
        const closestPoint = Math.round(percentage * totalPoints);

        if (this.data.draggingHandle === 'min') {
            // 确保最小值不超过最大值
            if (closestPoint < this.data.currentMax) {
                this.setData({
                    currentMin: closestPoint
                });
            }
        } else if (this.data.draggingHandle === 'max') {
            // 确保最大值不小于最小值
            if (closestPoint > this.data.currentMin) {
                this.setData({
                    currentMax: closestPoint
                });
            }
        }
    },

    /**
     * 根据选择的预算范围筛选商品
     * 这里可以添加实际的筛选逻辑
     */
    filterByBudget: function () {
        const minValue = this.data.sliderPoints[this.data.currentMin];
        const maxValue = this.data.sliderPoints[this.data.currentMax];

        console.log('筛选预算范围:', minValue, '-', maxValue);
        // 这里可以根据实际需求添加商品筛选逻辑
        // 例如调用API重新获取符合预算的商品列表
    },
    /**
     * 处理滑块点的点击事件
     * @param {Object} e 点击事件对象
     */
    onPointClick: function (e) {
        const index = e.currentTarget.dataset.index;
        const totalPoints = this.data.sliderPoints.length - 1;

        // 判断点击位置距离哪个滑块更近，决定更新最小值还是最大值
        const distanceToMin = Math.abs(index - this.data.currentMin);
        const distanceToMax = Math.abs(index - this.data.currentMax);

        // 如果点击的是当前选中范围外的点，优先更新离它更近的滑块
        if (index < this.data.currentMin || index > this.data.currentMax) {
            if (distanceToMin < distanceToMax) {
                this.setData({
                    currentMin: index
                });
            } else {
                this.setData({
                    currentMax: index
                });
            }
        } else {
            // 如果点击的是选中范围内的点，可以根据具体需求决定如何处理
            // 这里的逻辑是：如果点击的更靠近最小值，则更新最小值；更靠近最大值，则更新最大值
            if (distanceToMin < distanceToMax) {
                this.setData({
                    currentMin: index
                });
            } else if (distanceToMax < distanceToMin) {
                this.setData({
                    currentMax: index
                });
            }
            // 如果距离相等，我们可以选择不做任何操作，或者同时更新两个滑块
        }
    },

    getInfoApi: function () {
        var that = this;
        var paraArr = new Array();
        wx.request({
            url: rootDocment + '/api/goods/pianhao',
            data: {},
            method: 'GET',
            success: function (res) {
                that.setData({
                    list2: res.data.data
                })

            }
        })
    },

    // 点击
    clickSearchBtn(e) {
        let {
            type,
            name
        } = e.currentTarget.dataset

        if (type == 1) {
            name = this.data.list1Text == name ? '' : name
            this.setData({
                list1Text: name
            })
        } else if (type == 2) {
            name = this.data.list2Text == name ? '' : name
            this.setData({
                list2Text: name
            })
        } else if (type == 3) {
            name = this.data.list3Text == name ? '' : name
            this.setData({
                list3Text: name
            })
        }
    },

    findBtn() {
        this.filterByBudget();

        wx.navigateTo({
            url: `/subpage/gift_found/gift_found?text=${this.data.list2Text}`
        })
    },

    // 展开关闭
    toggleExpand: function () {
        this.setData({
            isExpanded: !this.data.isExpanded
        });
    },
});